<?php
namespace app\common\model;

use think\facade\Route;

class Article extends Model
{
    protected $autoWriteTimestamp = 'timestamp';

    // 状态列表
    const status_datalist = [
        0 => '关闭',
        1 => '开启',
    ];

    protected $searchOptions = [
        'title'       => ['like', '%%%s%%'],// 标题
        'content'     => ['like', '%%%s%%'],// 内容
        'category_id' => ['='],// 分类
    ];

    /**
     * 获取器：文章链接
     * @param null $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return url('Article/info', ['id' => $data['id']])->build();
    }

    /**
     * 获取详情html内容
     * @param $value
     * @param $data
     * @return string
     */
    public function getContentHtmlAttr($value, $data)
    {
        $content = \Michelf\MarkdownExtra::defaultTransform($data['content']);
        //$content = \Parsedown::instance()->text($data['content']);
        $content = preg_replace_callback('@<a href="(.*)"@iUs', function($matches) {
            if (preg_match('@^([a-zA-Z0-9-]+://|/|javascript:)@', $matches[1])) {
                return $matches[0];
            } else {
                return '<a href="' . Route::buildUrl($matches[1]) . '"';
            }
        }, $content);

        $content = str_replace('<img src="/storage', '<img src="//static.wampserver.site/storage', $content);

        return $content;
    }

    /**
     * 所属分类
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class)->withField(['id', 'title']);
    }
}